#include <shell.h>
#include <types.h>
#include <screen.h>
#include <string.h>
#include <yatak/rsa.h>
#include <libc/stdio.h>
#include <yatak/yatak.h>
#include <yatak/kheap.h>

extern char * decodeRsaMsg (int * msg, int size);

char * rsa_decoder (fs_node_t *file, unsigned int * seek)
{
	unsigned int sread;
	int count = 0;
	char * buff;
	int * cbuff;
	char * dbuff;
	if (!file)
		return NULL;
	
	buff = (char *) kmalloc(sizeof(char)*256);
	char * tbuff = buff;
	do
	{
		sread = fread_line(file, *seek, 256, buff);
		if (!sread)
		{
			uint32 sz = read_fs(file, *seek, 256, buff);
			if (sz)
			{
				sread = 1;
				*seek += sread;
				continue;
			}
			kfree (tbuff);
			return 0;
		}
		*seek += sread+1;
	}
	while (0);
	
	int i;
	for (i = 0; i < strlen (buff); i++)
	{
		if (buff [i] == ',')
			count++;
	}
	count++;
	
	cbuff = (int*)kmalloc(sizeof(int)*(count+1));
	i = 0;
	do
	{
		char * tmp = strsep(&buff,",");
		if (atoi(tmp))
			cbuff [i] = atoi(tmp);
		else
			break;
		i++;
	}
	while (buff);
	cbuff [i] = '\0';
	dbuff = decodeRsaMsg(cbuff,count+1);
	kfree (tbuff);
	kfree (cbuff);
	return dbuff;
}

void cat_decoder (char * param)
{
	fs_node_t *file = finddir_fs(GetCurrentNodeDir(), param);
	if (!file)
	{
		kprintf ("Cannot open file: %s\n", param);
		return;
	}
	uint32 flags;
	save_flags (flags);
	cli ();
	char * dbuff;
	int seek = 0;
	do
	{
		dbuff = rsa_decoder(file,&seek);
		if (!dbuff)
			break;
		kprintf ("%s\n",dbuff);
		kfree (dbuff);
	}
	while (1);
	restore_flags (flags);
}